package main

import (
	"net/http"
	"github.com/gin-gonic/gin"
	"gopkg.in/olahol/melody.v1"
	"sync"
	"fmt"
)

func main() {
	router := gin.Default()
	ws := melody.New()
	lock := new(sync.Mutex)

	router.GET("/", func(c *gin.Context) {
		http.ServeFile(c.Writer, c.Request, "index.html")
	})

	router.GET("/ws", func(c *gin.Context) {
		ws.HandleRequest(c.Writer, c.Request)
	})

	router.POST("/push", func(c *gin.Context) {
		lock.Lock()
		msg := c.PostForm("msg")
		if msg!="" {
			ws.Broadcast([]byte(msg))
		}
		lock.Unlock()
	})
	ws.HandleMessage(func(s *melody.Session, msg []byte) {
		lock.Lock()
		data := string(msg)
		fmt.Println(data)
		ws.Broadcast(msg)
		lock.Unlock()
	})
	router.Run(":5000")
}